﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SVM;
using MPI;

namespace ModelPredictPro.WindowForms {
   public static class Program {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]            
        static void Main(string[] args) {

            using (new MPI.Environment(ref args)) {
                TASK = new MPIServerClientTask();
                comm = TASK.Comm;
                Console.WriteLine("Node [{0}] start.", comm.Rank);

                if (TASK.IsServer) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new formMain());

                    TASK.ClientIDs.ToList().ForEach(o =>
                        TASK.Comm.Send<ParameterSelectionTaskUnitIn>(new ParameterSelectionTaskUnitIn { Problem = null, Param = null, NFold = int.MinValue }, o, 0));

                }
                else
                    RunClient();
                Console.WriteLine("Node [{0}] exit successfully.", comm.Rank);
            }
        }

        public static MPIServerClientTask TASK = null;
        static  Intracommunicator comm = null;
        static void RunClient() {

            Problem problem = null;
            while (true) {
                var unit = comm.Receive<ParameterSelectionTaskUnitIn>(0, 0);
                if (unit.NFold < 0)
                    break;
                if (problem == null)
                    problem = unit.Problem;
                double score = Training.PerformCrossValidation(problem, unit.Param, unit.NFold);
                comm.Send<ParameterSelectionTaskUnitOut>(new ParameterSelectionTaskUnitOut { CrossValidationScore = score, C = unit.Param.C, Gamma = unit.Param.Gamma, ClientId = comm.Rank }, 0, 0);
            }
        }
    }
}
